﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLDC.Common.Estate;
using System.Data;
using System.Text;
namespace ZLDC.Estate.Quantify
{
    public partial class TodayWorks : System.Web.UI.Page
    {
        protected string username;
        int sum = 0;
        int total = 0;
        private DataSet ds = null;
        public string value = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                value = ZLDC.Topo.BLL.Estate.lp_Basis.Exists_Set();
                div3.Visible = false;
                div5.Visible = false;

                ///隐藏接受，确定按钮
                btnSave1.Visible = false;
                btnSave2.Visible = false;
                anum.InnerHtml = "最低要求总分："+value;
                anum.Style["display"] = "none";
                ///隐藏稍候再说按钮
                if (_Request.GetString("type") == "1")
                {
                    //btnWait.Visible = false;
                }

                username = _Utility.GetInfoBySession().m_sUserName;

                string sql = "";
                
                //查询经理今天分配的工作类型
                string msgSQL = "select choiceType from lp_Configuration_main  where userID=" + _Utility.GetInfoBySession().m_sUserID + " and DATEDIFF(DD,workDay,GETDATE())=0 and isComplete=0 ";

                DataSet dsmsg = null;
                using (_Database msgdb = new _Database("estate"))
                {
                    dsmsg = msgdb.Query(msgSQL);
                }

                //判断是否已经确认接受工作 0为经理分配 1为自由选择 2已接受分配
                string choicetype = "";
                if (dsmsg.Tables[0].Rows.Count > 0)
                {

                    choicetype = dsmsg.Tables[0].Rows[0]["choiceType"].ToString();

                }

                ///绑定经理分配的套餐列表
                if (choicetype == "0")
                {

                    msgSQL = "select b.*,a.choiceType,c.Unit from lp_Configuration_main as a inner join  lp_Configuration as b on a.ID=b.mainId inner join lp_Basis as c on b.BasisCode=c.TypeCode   where b.Other1='1' and a.userID=" + _Utility.GetInfoBySession().m_sUserID + " and DATEDIFF(DD,a.workDay,GETDATE())=0 ";

                    using (_Database db = new _Database("estate"))
                    {
                        dsmsg = db.Query(msgSQL);
                    }

                    btnSave1.Visible = true;
                   
                    div3.Visible = true;
                    grView1.DataSource = dsmsg.Tables[0];
                    grView1.DataBind();
                    if (dsmsg.Tables[0].Rows.Count == 0)
                    {
                         
                    divtdcenter.InnerHtml = "经理未分配工作!<input id=\"Button1\" type=\"button\" value=\"关 闭\" onclick=\"parent.ClosePop()\" />";
               
                    }

                }
                else if (choicetype == "1")//自由分配工作
                {
                    div5.Visible = true;
                    btnSave2.Visible = true;
                    anum.Style["display"] = "";
                    ///查询是否是超过三个月的入职人员
                    ///
                    afk.InnerHtml = "经理请您自行安排工作!";
                    DataSet dsUser = null;
                    sql = "select  count(*) from v_usr_link where id=" + _Utility.GetInfoBySession().m_sUserID + " and  datediff(MM,rzsj,getdate()) >3 ";
                    using (_Database db = new _Database("estate"))
                    {
                        dsUser = db.Query(sql);
                    }

                    if (dsUser.Tables[0].Rows.Count > 0)
                    {

                        div5.Visible = true;

                        DataSet dsGrid = DataBind();

                        if (dsGrid.Tables[0].Rows.Count > 0)
                        {
                            grView2.DataSource = dsGrid;
                            grView2.DataBind();
                        }

                    }

                }
               

            }
            username = _Utility.GetInfoBySession().m_sUserName;



        }

        /// <summary>
        /// 绑定工作项
        /// </summary>
        /// <returns></returns>
        private static DataSet DataBind()
        {
            //string sqlstr = " select * from lp_Basis where dte=0 ";
            string sqlstr = "select * from lp_Configuration lc left join lp_Basis lb on lb.Name=lc.BasisName where lc.userID="+_Utility.GetInfoBySession().m_sUserID+""+
                            "and convert(varchar,lc.createtime,23)='"+DateTime.Now.ToString("yyyy-MM-dd")+"'";
            DataSet dsGrid = null;
            using (_Database db = new _Database("estate"))
            {
                dsGrid = db.Query(sqlstr);
            }
            return dsGrid;
        }

        
        protected void grView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                sum += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "SinglePoint") == null ? "0" : DataBinder.Eval(e.Row.DataItem, "SinglePoint"));
            }

            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = "总计：" ;
                e.Row.Cells[1].Text = sum.ToString();

            }
            //如果是绑定数据行 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //鼠标经过时，行背景色变 
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");
                //鼠标移出时，行背景色变 
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");

            }
           
        }
        string logo = "";
        int i = 0;
        int j = 0;
        protected void grView2_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "point"));
            }


            //如果是绑定数据行 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //鼠标经过时，行背景色变 
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");
                //鼠标移出时，行背景色变 
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");

            }
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    if (i == 0)
            //    {
            //        logo = DataBinder.Eval(e.Row.DataItem, "TypeName").ToString();
            //        i++;
            //    }
            //    else
            //    {
            //        if (logo == DataBinder.Eval(e.Row.DataItem, "TypeName").ToString())//如果这一行与上一行的相等
            //        {
            //            j++;
            //        }
            //        else
            //        {
            //            this.grView2.Rows[i - 1 - j].Cells[0].RowSpan = j + 1;
            //            for (int x = j; x > 0; x--)
            //            {
            //                this.grView2.Rows[i - x].Cells[0].Visible = false;
            //            }
            //            j = 0;
            //            logo = DataBinder.Eval(e.Row.DataItem, "TypeName").ToString();
            //        }
            //        i++;
            //    }
            //}
            //if (e.Row.RowType == DataControlRowType.Footer)
            //{
            //    this.grView2.Rows[i - 1 - j].Cells[0].RowSpan = j + 1;
            //    for (int x = j; x > 0; x--)
            //    {
            //        this.grView2.Rows[i - x].Cells[0].Visible = false;
            //    }
            //    j = 0;
            //    logo ="";
            //}

        }

        protected void grView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

            grView2.PageIndex = e.NewPageIndex;
            grView2.DataSource = DataBind();//绑定量化数据
            grView2.DataBind();
        }

        protected void btnSave2_Click(object sender, EventArgs e)
        {

            StringBuilder sb = new StringBuilder();
           
            decimal total = 0;
            Label lb = null;

            Label lblpoint = null;

            int count = 0;

            int newid = 0;

            if (grView2.Rows.Count > 0)
            {
                string msgSQL = "select * from lp_Configuration_main  where userID=" + _Utility.GetInfoBySession().m_sUserID + " and DATEDIFF(DD,workDay,GETDATE())=0 and isComplete=0  and  choicetype=1 ";
                DataSet ds = null;
                using (_Database db = new _Database("estate"))
                {
                    ds = db.Query(msgSQL);
                }

                if (ds.Tables[0].Rows.Count > 0)
                {
                    newid = _Convert.ToInt(ds.Tables[0].Rows[0]["id"].ToString(), 0);
                }

            }
            //string sql = "delete from lp_Configuration where userID = " + _Utility.GetInfoBySession().m_sUserID + " and DATEDIFF(dd, CreateTime, '" + DateTime.Now.ToString("yyyy-MM-dd") + "') = 0 ;";
            foreach (GridViewRow gvRow in grView2.Rows)
            {

                CheckBox cb = (CheckBox)gvRow.FindControl("cbxCheck");
                lb = (Label)gvRow.FindControl("lbltotal");//总分

                lblpoint = (Label)gvRow.FindControl("lblpoint");//分数
                Label lblquantity = (Label)gvRow.FindControl("lblquantity");//数量
                TextBox tbx = (TextBox)gvRow.FindControl("txtCount");//完成数量
                Label lblScore = (Label)gvRow.FindControl("lblScore");//最高分
                HiddenField BasisID = (HiddenField)gvRow.FindControl("hidBasisID");
                HiddenField hidid = (HiddenField)gvRow.FindControl("hidid");

                HiddenField hidHighest = (HiddenField)gvRow.FindControl("hidHighest");
                decimal SumScors=0;
                string Other1 = "0";//是否选中
                if (cb.Checked == true || cb.Enabled==false)
                {
                    if (lblScore.Text == "0")
                    {
                        SumScors = _Convert.ToDecimal(lblpoint.Text) / _Convert.ToDecimal(lblquantity.Text) * _Convert.ToDecimal(tbx.Text); //单项总分
                    }
                    else
                    {
                        SumScors = _Convert.ToDecimal(lblpoint.Text) / _Convert.ToDecimal(lblquantity.Text) * _Convert.ToDecimal(tbx.Text); //单项总分
                        if (SumScors >= _Convert.ToDecimal(lblScore.Text, 0))
                        {
                            SumScors = _Convert.ToDecimal(lblScore.Text);
                        }
                    }
                    total = total + SumScors;//各项总分

                    count++;
                    Other1 = "1";
                }
               
                DataSet ds = null;
                using (_Database db = new _Database("estate"))
                {
                    ds = db.Query(" select * from lp_basis where basisid=" + BasisID.Value + "");

                }
                string basisname = "";
                string typeCode = "";
                string typename = "";
                if (ds.Tables[0].Rows.Count > 0)
                {
                    basisname = ds.Tables[0].Rows[0]["name"].ToString();
                    typeCode = ds.Tables[0].Rows[0]["typecode"].ToString();
                    typename = ds.Tables[0].Rows[0]["typename"].ToString();
                }
                //sb.Append( " insert into lp_Configuration( ");
                //sb.Append(" mainId,BasisName,BasisCode,Point,Quantity,SystemSouce,SL,BasisPackage,CreateUser,CreateTime,userID,SinglePoint,Complete,Other1,Other2,Other3");
                //sb.Append(" )");
                //sb.Append(" values (");
                //sb.Append(" " + newid + ",'" + basisname + "','" + typeCode + "'," + (lblpoint.Text == "" ? "0" : lblpoint.Text) + "," + (tbx.Text == "" ? "0" : tbx.Text) + "," + SumScors + ",");
                //sb.Append("1,0,'" + _Utility.GetInfoBySession().m_sUserID + "','" + DateTime.Now + "'," + _Utility.GetInfoBySession().m_sUserID + "," + SumScors + ",0,'" + Other1 + "','" + _Utility.GetInfoBySession().m_sDeptID + "','" + typename + "'");
                //sb.Append(" )");

                sb.Append(" update lp_Configuration set TF=3,");
                sb.Append(" mainId=" + newid + ",BasisName='" + basisname + "',BasisCode='" + typeCode + "',Point=" + (lblpoint.Text == "" ? "0" : lblpoint.Text) + "");
                sb.Append(" ,Quantity=" + (tbx.Text == "" ? "0" : tbx.Text) + ",SystemSouce=" + hidHighest.Value + "");
                sb.Append(" ,SL=1,BasisPackage='',CreateUser=" + _Utility.GetInfoBySession().m_sUserID + ",CreateTime='" + DateTime.Now + "',userid=" + _Utility.GetInfoBySession().m_sUserID + "");
                sb.Append(" ,SinglePoint=" + SumScors + ",Complete=0,Other1='" + Other1 + "',Other2='" + _Utility.GetInfoBySession().m_sDeptID + "',Other3='"+typename+"' ");
                sb.Append(" where ID="+hidid.Value+"");
            }

            ZLDC.Topo.BLL.Estate.lp_Basis.lp_Configuration_main_add(sb.ToString());///插入量化项

            ///修改主表的总分数
            ZLDC.Topo.BLL.Estate.lp_Basis.lp_Configuration_main_add(" update lp_Configuration_main set choiceType=2,total=" + total + " where id=" + newid + "");

            //ZLDC.Common.Estate._Cookie.SetCookie("TodayWorks", "no");
            Response.Write("<script>parent.ClosePop();</script>");
            //System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, GetType(), "ajs", "window.returnValue='no';window.close();", true);
        }

        /// <summary>
        /// 接受工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave1_Click(object sender, EventArgs e)
        {
            string sSql = " update lp_Configuration_main set choiceType=2 where userID=" + _Utility.GetInfoBySession().m_sUserID + " and DATEDIFF(DD,workDay,GETDATE())=0 and isComplete=0";

            ZLDC.Topo.BLL.Estate.lp_Basis.Execution_sql(sSql);

            //ZLDC.Common.Estate._Cookie.SetCookie("TodayWorks", "no");

            //System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, GetType(), "ajs", "window.returnValue='no';window.close();", true);

            Response.Write("<script>parent.ClosePop();</script>");

        }

        protected void grView2_RowCreated(object sender, GridViewRowEventArgs e)
        {
           

        }

      
        protected string GetColor(object st)
        {
            if (st.ToString() == "客户工作类")
            { return "<div style='color:blue'>" + st + "</div>"; }
            else
            {

                return "<div style=''>" + st + "</div>"; ;
            }
        }
    }
}
